package com.ben.chatroom.common.cocurrent;

import com.ben.chatroom.common.util.ThreadUtils;
import com.google.common.util.concurrent.*;

import java.util.concurrent.Callable;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author huangyijun
 */
public class CallbackTaskScheduler {

  private final static ListeningExecutorService gPool;

  static {
    ThreadPoolExecutor jPool = ThreadUtils.getMixedTargetThreadPool();
    gPool = MoreExecutors.listeningDecorator(jPool);
  }

  private CallbackTaskScheduler() {
  }


  public static <R> void add(CallbackTask<R> task) {
    ListenableFuture<R> future = gPool.submit(task::execute);

    Futures.addCallback(future, new FutureCallback<R>() {
      @Override
      public void onSuccess(R t) {
        task.onBack(t);
      }

      @Override
      public void onFailure(Throwable throwable) {
        task.onException(throwable);
      }
    });
  }
}
